package com.nnxy.worktostudy.security.security;

import com.nnxy.worktostudy.security.entity.SecurityUser;
import com.nnxy.worktostudy.system.entity.Admin;
import com.nnxy.worktostudy.system.service.AdminService;
import com.nnxy.worktostudy.system.service.MenuService;
import com.nnxy.worktostudy.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author : lu'qz
 * @create 2021/9/26 0:06
 */
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private AdminService adminService;

    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.selectByUsername(username);

        admin.setPassword(MD5.encrypt(admin.getPassword()));            //TODO 增加添加管理员功能后删除此举，数据库密码未加密时使用

        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<String> permissionList = menuService.selectPermissionValueByUserId(admin.getId());
        SecurityUser user = new SecurityUser();
        user.setCurrentUserInfo(admin);
        user.setPermissionValueList(permissionList);

        return user;
    }
}
